#ifndef __CXL_UTIL_H__
#define __CXL_UTIL_H__

#include <stdint.h>
#include <stdbool.h>
#include <time.h>
#include "uv.h"

#define IMG_SAVE_DIR "/opt/Tim/tmp"

#define PIC_FILENAME_MAX_LEN 128

#ifndef MEM_SIZE
#define MEM_SIZE(type, member) sizeof(((type *)0)->member)
#endif

#ifndef FILE_CRC_ERROR
#define FILE_CRC_ERROR -1
#endif

#ifndef FILE_CRC_SUCCESS
#define FILE_CRC_SUCCESS 1
#endif

// 时间设置相关
#define BCD_TIME_LENGTH 6
#define DATE_TIME_STRING_LENGTH 20
typedef struct _app_time
{
    int tm_sec;  //代表目前秒数，正常范围为0-59，但允许至61秒
    int tm_min;  //代表目前分数，范围0-59
    int tm_hour; //从午夜算起的时数，范围为0-23
    int tm_mday; //目前月份的日数，范围01-31
    int tm_mon;  //代表目前月份，从一月算起，范围从0-11
    int tm_year; //从1900 年算起至今的年数
} __attribute__((__packed__)) AppTime;

#define container_of(ptr, type, member) (                                                 \
    {                                                                                     \
        const typeof(((type *)0)->member) *__mptr = (typeof(((type *)0)->member) *)(ptr); \
        (type *)((char *)__mptr - offsetof(type, member));                                \
    })

typedef struct
{
    uv_write_t req;
    uv_buf_t buf;
} write_req_t;

uint16_t crc(unsigned char *addr, uint32_t num);
int8_t calculate_file_crc(uint8_t *file_path, uint16_t *crc_p);
void bt();
bool setOpt(int fd, int nSpeed, int nBits, int nParity, int nStop);
bool mkdirCommon(uint8_t *path);
uint32_t getFilesNum(uint8_t *path);
int32_t getTimeString(uint8_t timeStr[12], uint8_t timeBcd[BCD_TIME_LENGTH]);
void genPicFileName(uint8_t fileName[PIC_FILENAME_MAX_LEN], uint8_t uniqueTag, uint8_t timeBcd[BCD_TIME_LENGTH], uint8_t camId, uint8_t picType);
int encode(char *buf, int size, const char *user, const char *pwd);

void get_time_value(const int8_t *buf, AppTime *sys_time);
int32_t chedaoji_set_time(AppTime *sys_time);
void time_bcd(uint8_t data[BCD_TIME_LENGTH]);
void time_bcd_from_time_t(time_t t, uint8_t data[BCD_TIME_LENGTH]);
int32_t bcd_time_to_string(const uint8_t bcd[BCD_TIME_LENGTH], uint8_t dst[DATE_TIME_STRING_LENGTH]);

/*** libuv相关 */
void initLoop();
uv_loop_t *getLoop();
uv_loop_t *getSqlLoop();
uv_loop_t *getPicDeleteLoop();
void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf);
void free_write_req(uv_write_t *req);

/**功能函数测试入口**/
void test_func();

#endif